<template>
  <section class="flex flex-col h-full">
    <el-form :model="queryParams" @submit.native.prevent ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="所属企业" prop="outTenantId">
        <el-select clearable filterable v-model="queryParams.outTenantId" placeholder="请选择所属企业" class="!w-200px">
          <el-option v-for="item in tenantList" :key="item.id" :label="item.enterName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="账号" prop="username">
        <el-input v-model="queryParams.username" :maxlength="50" placeholder="请输入账号" @keyup.enter="handleQuery"
          class="!w-200px" />
      </el-form-item>
      <el-form-item label="客户企业" prop="customerName">
        <el-input v-model="queryParams.customerName" :maxlength="50" @keyup.enter="handleQuery" placeholder="请输入客户企业"
          class="!w-200px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="flex justify-between mb-16px">
      <div>
        <el-button type="primary" @click="openAccountAuthForm" v-hasPermi="['dy:accountAuth']">账号授权</el-button>
        <el-button type="primary" @click="unBindAuth" v-hasPermi="['dy:unbind']">解绑</el-button>
      </div>
      <div>
        <el-button @click="toggle">
          <el-tooltip effect="dark" content="全屏" placement="top-start">
            <div style="width: 22px;height: 22px;">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                <path d="M8 3V5H4V9H2V3H8ZM2 21V15H4V19H8V21H2ZM22 21H16V19H20V15H22V21ZM22 9H20V5H16V3H22V9Z"></path>
              </svg>
            </div>
          </el-tooltip>
        </el-button>
      </div>
    </div>
    <el-table class="flex-1" ref="singleTableRef" v-loading="loading" :data="list" border stripe
      @selection-change="selectionChange" :span-method="objectSpanMethod"
      :header-cell-style="{ background: '#F3F4F7', color: '#555' }" height="100%">
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column label="所属企业" align="left" prop="outTenantName" min-width="120" fixed="left"
        :show-overflow-tooltip="true">
        <template #default="{row}">
          {{row.outTenantName}}
        </template>
      </el-table-column>
      <el-table-column label="账号" align="left" prop="username" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="left" prop="status" min-width="150" :show-overflow-tooltip="true">
        <template #header>
          <el-container>
            <div>状态</div>
            <div class="th-text">(账号状态+密码)</div>
          </el-container>
        </template>
        <template #default="{row}">
          <el-tooltip v-if="row.status===1 && row.statusDesc" effect="dark" :content="row.statusDesc"
            placement="top-start">
            <StatusText :type="DICT_TYPE.ACCOUNT_STATUS" :value="row.status" :isJL="false"
              :color="colorStatusMap[row.status]">
            </StatusText>
          </el-tooltip>
          <StatusText v-else :type="DICT_TYPE.ACCOUNT_STATUS" :value="row.status" :isJL="false"
            :color="colorStatusMap[row.status]">
          </StatusText>
        </template>
      </el-table-column>
      <el-table-column label="身份" align="left" prop="identity" min-width="100" :show-overflow-tooltip="true">
        <template #default="{row}">
          {{getDictLabel(DICT_TYPE.ACCOUNT_IDENTITY,row.identity)}}
        </template>
      </el-table-column>
      <el-table-column label="客户企业" align="left" prop="customerName" min-width="150" :show-overflow-tooltip="true">
        <template #header>
          <el-container class="flex items-center">
            <span>客户企业</span>
            <el-tooltip effect="dark" content="销售客户/中转客户">
              <el-icon :color="color1" :size="20" class="ml-4px cursor-pointer" @mouseover="color1='#409EFE'"
                @mouseleave="color1='#909399'">
                <WarningFilled />
              </el-icon>
            </el-tooltip>
          </el-container>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="left" prop="resource" min-width="100" :show-overflow-tooltip="true">
        <template #default="{row}">
          {{getDictLabel(DICT_TYPE.DATA_IDENTITY,row.resource)}}
        </template>
      </el-table-column>
      <el-table-column label="授权时间" align="left" prop="authorizeTime" min-width="170" :show-overflow-tooltip="true" />
      <el-table-column label="更新时间" align="left" prop="updateTime" min-width="170" :show-overflow-tooltip="true" />
      <el-table-column label="数据共享企业" align="left" prop="dataShareInfosText" min-width="150"
        :show-overflow-tooltip="true">
        <template #header>
          <el-container class="flex items-center">
            <span>数据共享企业</span>
            <el-tooltip effect="dark" content="可使用该数据权限的货主企业名称">
              <el-icon :color="color2" :size="20" class="ml-4px cursor-pointer" @mouseover="color2='#409EFE'"
                @mouseleave="color2='#909399'">
                <WarningFilled />
              </el-icon>
            </el-tooltip>
          </el-container>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" prop="roseAndFallIndex" width="100" fixed="right">
        <template #default="{row}">
          <el-container v-hasPermi="['dy:dataShare']">
            <el-button v-if="row.bindShareDataBtn===1" link type="primary"
              @click="dataSourceShare(row.authorizeDataId)">
              数据共享
            </el-button>
          </el-container>
          <el-container v-hasPermi="['dy:cancelShare']">
            <el-button v-if="row.unbindShareDataBtn===1" link type="primary"
              @click="cancelDataSourceShare(row.authorizeDataId)">
              取消共享
            </el-button>
          </el-container>
        </template>
      </el-table-column>
    </el-table>
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
    <AccountAuthForm ref="accountAuthFormRef" @success="getOutTenantList();resetQuery()"></AccountAuthForm>
    <ShareForm ref="shareFormRef" @success="resetQuery"></ShareForm>
  </section>
</template>
<script setup lang="ts" name="AuthorizationManage">
  import * as authorizationManageApi from '@/api/authorizationManage'
  import { DICT_TYPE, getIntDictOptions, getDictLabel } from '@/utils/dict'
  import AccountAuthForm from './accountAuthForm.vue'
  import { useFullscreen } from '@vueuse/core'
  import ShareForm from './shareForm.vue'
  import { cloneDeep } from 'lodash'

  const loading = ref(false)
  const tenantList = ref([])
  const total = ref(0)
  const list = ref([])
  const queryFormRef = ref()
  const color1 = ref('#909399')
  const color2 = ref('#909399')
  const singleTableRef = ref()
  const message = useMessage()
  const shareFormRef = ref()
  const accountAuthFormRef = ref()
  const colorStatusMap = ref({
    1: 'red',
    0: 'blue'
  })
  const { isFullscreen, toggle } = useFullscreen(singleTableRef)
  const queryParams = ref({
    pageNo: 1,
    pageSize: 10,
    username: undefined,
    outTenantId: undefined,
    customerName: undefined
  })

  const selectionChange = (selection) => {
    if (selection.length > 1) {
      singleTableRef.value.clearSelection()
      singleTableRef.value.toggleRowSelection(selection[selection.length - 1])
    }
  }

  const unBindAuth = async () => {
    const row = singleTableRef.value.getSelectionRows()
    const ids = row.map(e => e.id)
    if (ids.length === 0) {
      message.warning('请选择所属企业')
      return
    }
    await message.confirm('您确认解绑该授权账号吗？ 解绑后则不能查询该企业数据')
    await authorizationManageApi.unbindAuthorize(ids)
    message.success('解绑成功')
    getOutTenantList()
    resetQuery()
  }

  const openAccountAuthForm = () => {
    accountAuthFormRef.value.open()
  }

  const dataSourceShare = (id) => {
    shareFormRef.value.open(id)
  }

  const cancelDataSourceShare = async (id) => {
    await message.confirm('您确认取消为该企业共享数据吗 ？')
    await authorizationManageApi.unbindDataShare(id)
    message.success('取消共享成功')
    resetQuery()
  }

  const objectSpanMethod = (item) => {
    const { columnIndex, row } = item
    if ([0, 1, 2, 3].includes(columnIndex)) {
      if (row.isMerge) {
        return {
          rowspan: row.index,
          colspan: 1,
        }
      } else {
        return {
          rowspan: 0,
          colspan: 0,
        }
      }
    }
  }

  const getOutTenantList = async () => {
    const res = await authorizationManageApi.getOutTenantList()
    tenantList.value = res || []
  }

  const getList = async () => {
    loading.value = true
    try {
      const res = await authorizationManageApi.accountAuthorizePage(queryParams.value)
      total.value = res?.total || 0
      list.value = handleList(res.list || [])
    } finally {
      loading.value = false
    }
  }

  const handleList = (list) => {
    return list.map(e => {
      if (e.authorizeDataList?.length) {
        return e.authorizeDataList.map((m, n) => {
          return {
            isMerge: n === 0,
            index: e.authorizeDataList.length,
            ...e,
            ...m,
            dataShareInfosText: (m.dataShareInfos || []).map(s => s.shareEnterpriseName).join(',')
          }
        })
      } else {
        return {
          isMerge: true,
          index: 1,
          ...e
        }
      }
    }).flat(Infinity)
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNo = 1
    getList()
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
  }

  /** 初始化 **/
  onMounted(async () => {
    await getOutTenantList()
    getList()
  })
</script>
<style lang="scss" scoped>
  .el-button+.el-button {
    margin-left: 10px;
  }

  :deep(.el-table__header-wrapper .el-checkbox__inner) {
    display: none !important;
  }

  :deep(.el-table__header-wrapper .el-checkbox__input::after) {
    content: '单选';
    color: rgb(85, 85, 85);
    font-weight: bold;
  }

  .th-text {
    font-size: 12px;
    color: #909399;
  }

  .el-table {
    :deep(.el-button) {
      height: 30px !important;
      line-height: 30px !important;
    }
  }

  :deep(.el-form-item--default) {
    margin-bottom: 16px;
  }

  :deep(.el-table .cell) {
    line-height: 30px;
  }
</style>